﻿using Smart.Model;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static partial class Net
{
    static Dictionary<int, System.Action<Google.Protobuf.IMessage>> mHandlers = new Dictionary<int, System.Action<Google.Protobuf.IMessage>>(512);
    public static void Init()
    {
        Log.Info("[网络模块]:注册网络消息...");
        mHandlers.Clear();
        Register();
    }

    public static void Clear()
    {
        mHandlers.Clear();
    }

    public static void AddHandler<T>(int msgId,System.Action<T> handler)
    {
        if(!mHandlers.ContainsKey(msgId) && null != handler)
        {
            System.Action<Google.Protobuf.IMessage> act = (Google.Protobuf.IMessage msg) =>
            {
                if (msg is T impl)
                {
                    handler(impl);
                }
            };
            mHandlers.Add(msgId,act);
        }
    }

    public static void HandleNetMsg(int msgId,Google.Protobuf.IMessage message)
    {
        if(!mHandlers.TryGetValue(msgId, out var handlder))
        {
            Log.Error($"[HandleNetMsg]:{msgId} has no handler yet ...");
            return;
        }

        handlder(message);

        // try
        // {
        //     mHandlers[msgId](message);
        //     MessagePool.Instance.Recycle(message);
        // }
        // catch(System.Exception e)
        // {
        //     Log.Error($"[HandleNetMsg]:{msgId} handle error");
        //     Log.Error($"[HandleNetMsg]:{e.Message}");
        //     Log.Error($"[HandleNetMsg]:{e.StackTrace}");
        // }
    }
}